﻿using System.Collections.Generic;
using System.Text;

namespace LujWeb.Internal;

internal class PageTemplateRender {

  public string Render(string template, PageTemplateVar[] varList, IDictionary<string, string> data) {
    StringBuilder result = new(template.Length * 2);

    var getVal = (PageTemplateVar info) => {
      if (data.TryGetValue(info.Name, out var val)) {
        return val;
      }
      return template[info.Start..info.End];
    };

    int prevEnd = 0;
    foreach (PageTemplateVar varInfo in varList) {
      int varStart = varInfo.Start;
      result.Append(template[prevEnd..varStart]);
      result.Append(getVal(varInfo));
      prevEnd = varInfo.End;
    }

    if (prevEnd < template.Length) {
      result.Append(template[prevEnd..]);
    }

    return result.ToString();
  }
}
